import { createRouter, createWebHistory } from 'vue-router'
import sysRoutes from './routes'
import { useTokenStore } from '@/stores/token';
import { useMenusStore } from '@/stores/menus';


const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: sysRoutes
})


// 菜单初始化
let isInitMenu = false

router.beforeEach(async (to, form) => {
  const tokenStore = useTokenStore()
  if (!tokenStore.isLogin && to.name !== 'login') {
    return { name: 'login', query: { redirect: to.fullPath} }
  }
  // 登录后的逻辑
  const menusStore = useMenusStore()
  if (!isInitMenu && tokenStore.isLogin){
    isInitMenu = true
    // 这里动态添加路由
    menusStore.treeMenusDataAddRouter(router)
    return to.fullPath
  }
  return true
})



export default router
